<template>
  <!-- Row 角色管理 start -->
  <Row :gutter="10">
    <!-- Col 左侧角色列表模块 start -->
    <Col :lg="5" :md="8">
      <Card class="warp-card" dis-hover style=" position: relative;">
        <p slot="title">角色管理</p>
        <div slot="extra">
          <Button
            @click="showAddRoleModal()"
            size="small"
            type="primary"
            v-privilege="'add-role'"
          >新增</Button>
        </div>
        <!-- Menu 角色列表 start -->
        <Menu
          :active-name="0"
          class="left role-list no-scrollbar"
          ref="sideMenu"
          style="height: 666px;overflow-y: scroll;width:100%;"
        >
          <!-- MenuItem 角色列表项 start -->
          <MenuItem
            :key="item.id"
            :name="index"
            @click.native="selectRole(item,index)"
            v-for="(item,index) in roleList"
          >
            <Row>
              <Col span="24">
                <span class="role-name">
                  <Tooltip placement="right">
                    <span>{{item.roleName}}</span>
                    <div class="suspension-box" slot="content">
                      <p>
                        <span @click="deleteSingleRole(item)" v-privilege="'delete-role'">删除</span>
                      </p>
                      <p>
                        <span @click="showUpdateRoleModal(item)" v-privilege="'update-role'">编辑</span>
                      </p>
                    </div>
                  </Tooltip>
                </span>
              </Col>
            </Row>
          </MenuItem>
          <!-- MenuItem 角色列表项 end -->
        </Menu>
        <!-- Menu 角色列表 end -->
        <!--Modal 添加角色 start-->
        <Modal title="新增角色"
        :loading="isShowSaveLoading"
        :closable="false"
        width="740"
        v-model="isShowAddRoleModal"
        >
          <Form  :label-width="80" :model="saveItem" :rules="saveValidate"  ref="saveRef">
            <FormItem label="角色名称" required prop="roleName">
              <Input
                @on-keydown="saveItem.roleName=saveItem.roleName.replace(/^ +| +$/g,'')"
                @on-keyup="saveItem.roleName=saveItem.roleName.replace(/^ +| +$/g,'')"
                placeholder="请输入角色名称"
                v-model="saveItem.roleName"
              ></Input>
            </FormItem>
            <FormItem label="描述" prop ="remark">
              <Input placeholder="请输入描述"
              :autosize="{minRows: 5, maxRows: 8 }"
              :maxlength="maxlength"
              @input="descInput"
              type="textarea" v-model="saveItem.remark"></Input>
              <span class="text">{{ remnant }}/{{maxlength}}</span>
            </FormItem>
          </Form>
          <div slot="footer">
            <Button
              @click="cancelSaveData"
            >取消</Button>
            <Button
              type="primary"
              @click="validateAndAddRole"
            >确定</Button>
          </div>
        </Modal>
        <Modal title="修改角色"
          :loading="isShowUpdateLoading"
          @on-cancel="cancelUpdateData"
          @on-ok="validateAndUpdateRole"
          :closable="false"
          width="740"
          v-model="isShowUpdateRoleModal">
          <Form :label-width="80" :model="updateItem" :rules="updateValidate"  ref="updateRef">
            <FormItem  label="角色名称" required prop="roleName">
              <Input
                @on-keydown="updateItem.roleName=updateItem.roleName.replace(/^ +| +$/g,'')"
                @on-keyup="updateItem.roleName=updateItem.roleName.replace(/^ +| +$/g,'')"
                placeholder="请输入角色名称"
                v-model="updateItem.roleName"
              ></Input>
            </FormItem>
            <FormItem label="描述" prop ="remark">
              <Input placeholder="请输入描述"
                :maxlength="maxlength"
                :autosize="{minRows: 5, maxRows: 8 }"
               type="textarea"
               @input="descInput"
               v-model="updateItem.remark"></Input>
            <span class="text">{{ remnant }}/{{maxlength}}</span>
            </FormItem>
          </Form>
          <div slot="footer">
            <Button
              @click="cancelUpdateData"
            >取消</Button>
            <Button
              type="primary"
              @click="validateAndUpdateRole"
            >确定</Button>
          </div>
        </Modal>
        <!--Modal 修改角色 end-->
        <!--Modal 删除角色 start-->
        <Modal
          @on-cancel="cancelDeleteRole()"
          @on-ok="confirmDeleteRole()"
          title="删除角色"
          v-model="isShowRemoveRoleModal"
        >确定删除"{{ruleDetail.roleName}}"这个角色吗？</Modal>
        <!--Modal 删除角色 end-->
      </Card>
    </Col>
    <!-- Col 左侧角色列表模块 end -->
    <!-- Col 功能列表 start -->
    <Col :lg="19" :md="16">
      <Card class="warp-card" dis-hover>
        <div class="card-title" slot="title">功能列表</div>
        <!-- Menu 切换功能 start -->
        <Menu :active-name="displayTab" @on-select="selectTab" mode="horizontal" style="z-index: 1">
          <MenuItem :name="1">
            <Icon type="ios-hammer" />功能权限
          </MenuItem>
          <MenuItem :name="2">
            <Icon type="ios-paper" />数据范围
          </MenuItem>
          <MenuItem :name="3">
            <Icon type="ios-people" />成员管理
          </MenuItem>
        </Menu>
        <!-- Menu 切换功能 end -->
        <!--功能权限-->
        <RoleTree :roleId="roleId" v-if="displayTab==1"></RoleTree>
        <!--数据范围-->
        <RoleDataScope :roleId="roleId" v-if="displayTab==2"></RoleDataScope>
        <!--成员管理-->
        <RoleList :roleId="roleId" v-if="displayTab==3"></RoleList>
      </Card>
    </Col>
    <!-- Col 功能列表 end -->
  </Row>
  <!-- Row 角色管理 end -->
</template>
<script>
import RoleTree from './components/role-tree/role-tree';
import { validateTextLength } from '@/lib/util';
import RoleList from './components/role-list/role-list';
import RoleDataScope from './components/role-data-scope/role-data-scope';
import { roleApi } from '@/api/role';

export default {
  name: 'RoleManage',
  components: {
    RoleTree,
    RoleList,
    RoleDataScope
  },
  props: {},
  data() {
    return {
      roleList: [],
      roleId: 0,
      remnant: 200,
      maxlength:200,
      // 删除角色对话框隐藏
      isShowRemoveRoleModal: false,
      // 修改角色对话框隐藏
      isShowUpdateRoleModal: false,
      isShowSaveLoading: true,
      isShowUpdateLoading: true,
      // 增加角色对话框隐藏
      isShowAddRoleModal: false,
      // 增加角色信息
      ruleDetail: {
        roleName: '',
        id: '',
        remark: ''
      },
      // 更新的数据
      updateItem: {
        roleName: '',
        id: 0,
        remark: ''
      },
      // 添加保存的数据
      saveItem: {
        roleName: '',
        remark: ''
      },
      // 默认选中Menu标签为功能权限
      displayTab: 1,
      // 是否第一次请求数据
      isFirst: true,
      updateValidate: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      saveValidate: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
      },
    };
  },
  computed: {},
  watch: {
    isShowAddRoleModal(val) {
      if (val) {
        this.remnant = 0
      }
    }
  },
  filters: {},
  created() {},
  mounted() {
    // 初始化加载数据
    this.getAllRole();
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
  methods: {
    // 初始化加载数据方法
    async getAllRole() {
      try {
        let response = await roleApi.getAllRole();
        this.roleList = response.data;
        if (this.roleList && this.roleList.length > 0) {
          this.roleId = this.roleList[0].id;
          if (this.isFirst) {
            this.$nextTick(() => {
              this.$refs.sideMenu.updateOpened();
              this.$refs.sideMenu.updateActiveName();
            });
            this.isFirst = false;
          }
        }
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
      }
    },
     descInput() {
      let remark = this.updateItem.id?this.updateItem.remark:this.saveItem.remark;
      let txtVal = validateTextLength(remark);
      this.remnant = this.maxlength - txtVal;
    },
    // 增加角色方法
    async addRole() {
      this.$Spin.show();
      try {
        let result = await roleApi.addRole(this.saveItem);
        this.$Message.success('新增成功');
        this.$emit('addSuccess');
        await this.getAllRole(); // 刷新
        this.cancelSaveData();
      } catch (e) {
        this.isShowSaveLoading = false;
        this.$nextTick(() => {
          this.isShowSaveLoading = true;
        });
      } finally {
        this.isShowSaveLoading = false;
        this.$Spin.hide();
      }
    },
     // 编辑角色方法
    async updateRole() {
      this.$Spin.show();
      try {
        let response = await roleApi.updateRole(this.updateItem);
        this.$Message.success('修改成功');
        this.$emit('updateSuccess');
        this.roleList = response.data;
        await this.getAllRole(); // 刷新
        this.cancelUpdateData();
      } catch (e) {
        this.isShowUpdateLoading = false;
        this.$nextTick(() => {
          this.isShowUpdateLoading = true;
        });
        console.error(e);
      } finally {
        this.isShowUpdateLoading = false;
        this.$Spin.hide();
      }
    },
    validateAndUpdateRole() {
      this.$refs['updateRef'].validate(valid => {
        this.isShowUpdateLoading = true;
        if (valid) {
          this.updateRole();
        } else {
          this.isShowUpdateLoading = false;
          this.$nextTick(() => {
            this.isShowUpdateLoading = true;
          });
        }
      });
    },
    validateAndAddRole() {
      try {
        this.$refs['saveRef'].validate(valid => {
          this.isShowSaveLoading = true;
          if (valid) {
              this.addRole();
          } else {
            this.isShowSaveLoading = false;
            this.$nextTick(() => {
              this.isShowSaveLoading = true;
            });
          }
        });
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
      }
    },
    // 清除添加模态框数据
    cancelSaveData() {
      Object.assign(this.saveItem, this.saveItemInt);
      // 清空form规则检查
      this.$refs['saveRef'].resetFields();
      this.isShowAddRoleModal = false;
    },
    // 清除编辑模态框数据
    cancelUpdateData() {
      this.updateItem = {};
      // 清空form规则检查
      this.$refs['updateRef'].resetFields();
      this.isShowUpdateRoleModal = false;
    },
    // 删除角色方法
    async deleteRole(id) {
      this.$Spin.show();
      try {
        await roleApi.deleteRole(id);
        this.$Message.success('删除成功');
        await this.getAllRole(); // 刷新
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
      } finally {
        this.$Spin.hide();
      }
    },
    // 删除单个角色
    deleteSingleRole(item) {
      this.isShowRemoveRoleModal = true;
      this.ruleDetail.id = item.id;
      this.ruleDetail.roleName = item.roleName;
    },
    // 编辑角色页面
    showUpdateRoleModal(item) {
      this.isShowUpdateRoleModal = true;
      this.updateItem.id = item.id;
      this.updateItem.roleName = item.roleName;
      this.updateItem.remark = item.remark;
      this.descInput();
    },
    // 添加角色页面
    showAddRoleModal() {
      this.isShowAddRoleModal = true;
      this.saveItem.roleName = '';
      this.saveItem.remark = '';
    },
    // 关闭更新弹窗
    hideUpdateRoleModal() {
      this.isShowUpdateRoleModal = false;
    },
    // 关闭添加弹窗
    hideAddRoleModal() {
      this.isShowAddRoleModal = false;
    },
    // 功能选择
    selectTab(position) {
      this.displayTab = position;
    },
    // 角色选择
    selectRole(item, index) {
      this.roleId = item.id;
    },
    // 确定删除
    confirmDeleteRole() {
      this.deleteRole(this.ruleDetail.id);
      this.isShowRemoveRoleModal = false;
    },
    // 取消删除
    cancelDeleteRole() {
      this.isShowRemoveRoleModal = false;
    }
  }
};
</script>
<style lang="less" scoped>
.role-list {
  line-height: 30px;
  padding: 10px 0;

  .role-name {
    position: relative;
  }

  &::after {
    display: none;
  }

  button {
    margin-left: 3px;
  }
}

.ivu-menu-item-active:not(.ivu-menu-submenu) {
  z-index: 0 !important;
}

.suspension-box {
  z-index: 999;
  padding: 0 8px;

  p {
    padding: 3px 0;
  }
}
.text{
    position: absolute;
    right: 10px;
    bottom: -5px;
}
</style>
